<template>
	<el-row>
		<el-col :span="24">
			<el-card>
				<el-row :gutter="20">
					<el-col :span="16">
						<el-button type="success" style="margin-bottom: 10px; margin-right: 20px; float: left;"
							@click="showAddElderlyModel">新增
            </el-button>
					</el-col>
					<el-col :span="8">
						<div style="width: 540px; float: right; margin-right: 10px;">
							<el-input v-model="eusername" style="width: 200px; float: right;" placeholder="请输入查询的用户名"
								clearable :prefix-icon="Search" @input="selectAll(1)" />
							<el-input v-model="ename" style="width: 200px; float: right; margin-right: 20px"
								placeholder="请输入查询的姓名" clearable :prefix-icon="Search" @input="selectAll(1)" />
						</div>
					</el-col>
				</el-row>
				<el-table :data="allElderly.list" border style="width: 100%; margin-top: 30px;">
					<el-table-column prop="eid" label="ID" width="50px" />
					<el-table-column prop="ename" label="姓名" width="100px" />
					<el-table-column prop="picdir" label="头像" width="110px">
						<template #default="scope">
							<el-avatar :size="80" :src="`${SERVER_ADDR}/upload/${scope.row.picdir}`"></el-avatar>
						</template>
					</el-table-column>
					<el-table-column prop="egender" label="性别" width="80px" />
					<el-table-column prop="eusername" label="用户名" width="120px" />
					<el-table-column prop="dateBirth" label="出生日期" width="120px" />
					<el-table-column prop="checkDate" label="入住日期" width="120px" />
					<el-table-column prop="emergencyContact" label="紧急联系人" width="200px" />
					<el-table-column prop="room.rno" label="房间号" width="80px" />
					<el-table-column label="操作" width="350px">
						<template #default="scope">
							<el-button type="primary" style="width: 15px;" :icon="View"
								@click="getElderlyInfo(scope.row.eid)" />
							<el-popover placement="top-start" title="照顾该老人的护工" :width="400" trigger="hover">
								<slot>
									<el-table :data="scope.row.medicalStaffs" border>
										<el-table-column prop="mno" label="ID" />
										<el-table-column prop="mname" label="姓名" />
										<el-table-column prop="mphone" label="联系电话" />
									</el-table>
								</slot>
								<template #reference>
									<el-button type="warning"
										@click="showAddEmpModel('', scope.row.eid)">添加护工</el-button>
								</template>
							</el-popover>

							<el-button type="primary" @click="showUpdateEldrlyModel(scope.row.eid)">修改</el-button>
							<el-popconfirm title="你确定删除该老人吗？" confirm-button-text="确定" cancel-button-text="取消"
								@confirm="deleteByeid(scope.row.eid)">
								<template #reference>
									<el-button type="danger">删除</el-button>
								</template>
							</el-popconfirm>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页开始 -->
				<el-row class="row-bg" justify="center">
					<el-col :span="5">
						<div class="grid-content ep-bg-purple" />
					</el-col>
					<el-col :span="8">
						<el-pagination background layout="prev, pager, next" :page-count="allElderly.pages"
							@change="selectAll" style="margin-top: 10px; margin-left: 25%;"
							v-model:urrent-page="allElderly.pageNum" />
					</el-col>
					<el-col :span="5">
						<div class="grid-content ep-bg-purple" />
					</el-col>
				</el-row>
				<!-- 分页结束 -->
			</el-card>
		</el-col>
	</el-row>
	<!-- 老人详细信息框开始 -->
	<el-drawer v-model="drawer" title="老人的详细信息" :with-header="false">
		<el-descriptions title="老人的详细信息" direction="vertical" border style="margin-top: 20px">
			<el-descriptions-item :rowspan="2" :width="140" label="照片" align="center">
				<el-image style="width: 100px; height: 100px"
					:src="`${SERVER_ADDR}/upload/${elderlyInfo.picdir}`" />
			</el-descriptions-item>
			<el-descriptions-item label="老人姓名">{{ elderlyInfo.ename }}</el-descriptions-item>
			<el-descriptions-item label="老人电话">{{ elderlyInfo.phone }}</el-descriptions-item>
			<el-descriptions-item label="性别">{{ elderlyInfo.egender }}</el-descriptions-item>
			<el-descriptions-item label="身份证号码">
				{{ elderlyInfo.idCard }}
			</el-descriptions-item>
			<el-descriptions-item label="用户名">{{ elderlyInfo.eusername }}</el-descriptions-item>
			<el-descriptions-item label="密码">
				<span v-if="elderlyInfo.estate == 1">
					<el-tag type="success">已入住</el-tag>
				</span>
				<span v-else-if="elderlyInfo.estate == 3">
					<el-tag type="danger">退房</el-tag>
				</span>
			</el-descriptions-item>
			<el-descriptions-item label="出生时间">{{ elderlyInfo.dateBirth }}</el-descriptions-item>
			<el-descriptions-item label="入住时间">{{ elderlyInfo.checkDate }}</el-descriptions-item>
		</el-descriptions>
	</el-drawer>
	<!-- 老人详细信息框结束 -->
	<!-- 添加员工穿梭框开始 -->
	<el-dialog v-model="addDialoadShow" title="添加护工">
		<el-transfer
        v-model="addMids"
        filterable
        :data="addEldList"
        :titles="['可选护工', '已选护工']"
    />
		<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" @click="addMedical">确定</el-button>
				<el-button @click="addDialoadShow = false">取消</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 新增员工穿梭框结束 -->
	<!-- 新增老人对话框开始 -->
	<el-dialog v-model="addDialoadShowElderly" title="新增老人" width="500">
		<el-form :model="addElderly" :rules="rules" ref="addElderlyFrom">
			<el-form-item label="头像" label-width="20%">
				<el-upload class="avatar-uploader" :action="`${SERVER_ADDR}/admin/file/upload`" name="pic"
					:headers="headers" :show-file-list="false" :on-success="handleAvatarSuccessAdd"
					:before-upload="beforeAvatarUpload">
					<img v-if="imageUrlAdd" :src="imageUrlAdd" class="avatar" />
					<el-icon v-else class="avatar-uploader-icon">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="姓名" label-width="20%" prop="ename">
				<el-input v-model="addElderly.ename" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="用户名" label-width="20%" prop="eusername">
				<el-input v-model="addElderly.eusername" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="密码" label-width="20%" prop="epassword">
				<el-input v-model="addElderly.epassword" type="password" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="性别" label-width="20%">
				<el-radio-group v-model="addElderly.egender">
					<el-radio value="男" border>男</el-radio>
					<el-radio value="女" border>女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="出生日期" label-width="20%">
				<el-date-picker v-model="addElderly.dateBirth" type="date" placeholder="请选择一个时间" format="YYYY-MM-DD"
					value-format="YYYY-MM-DD" style="width: 240px" />
			</el-form-item>
			<el-form-item label="入住日期" label-width="20%">
				<el-date-picker v-model="addElderly.checkDate" type="date" placeholder="请选择一个时间" format="YYYY-MM-DD"
					value-format="YYYY-MM-DD" style="width: 240px" />
			</el-form-item>
			<el-form-item label="身份证" label-width="20%">
				<el-input v-model="addElderly.idCard" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="紧急联系人" label-width="20%" prop="emergencyContact">
				<el-input v-model="addElderly.emergencyContact" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="联系电话" label-width="20%" prop="phone">
				<el-input v-model="addElderly.phone" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="所在房间" label-width="20%">
				<el-select v-model="addElderly.rid" clearable placeholder="所在房间" style="width: 240px">
					<el-option v-for="item in roomAll" :key="item.rid" :label="item.rno" :value="item.rid" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="addDialoadShowElderly = false">取消</el-button>
				<el-button type="primary" @click="insertByElderly(addElderlyFrom)">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 新增老人对话框结束 -->
	<!-- 修改老人对话框开始 -->
	<el-dialog v-model="updateDialoadShowElderly" title="修改老人" width="500">
		<el-form :model="updateEldrly" :rules="rules" ref="updateElderlyFrom">
			<el-form-item label="头像" label-width="20%">
				<el-upload class="avatar-uploader" :action="`${SERVER_ADDR}/admin/file/upload`" name="pic"
					:headers="headers" :show-file-list="false" :on-success="handleAvatarSuccessUpdate"
					:before-upload="beforeAvatarUpload">
					<img v-if="imageUrlUpdate" :src="imageUrlUpdate" class="avatar" />
					<el-icon v-else class="avatar-uploader-icon">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="姓名" label-width="20%" prop="ename">
				<el-input v-model="updateEldrly.ename" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="用户名" label-width="20%" prop="eusername">
				<el-input v-model="updateEldrly.eusername" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="性别" label-width="20%">
				<el-radio-group v-model="updateEldrly.egender">
					<el-radio value="男" border>男</el-radio>
					<el-radio value="女" border>女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="出生日期" label-width="20%">
				<el-date-picker v-model="updateEldrly.dateBirth" type="date" placeholder="请选择一个时间" format="YYYY-MM-DD"
					value-format="YYYY-MM-DD" style="width: 240px" />
			</el-form-item>
			<el-form-item label="入住日期" label-width="20%">
				<el-date-picker v-model="updateEldrly.checkDate" type="date" placeholder="请选择一个时间" format="YYYY-MM-DD"
					value-format="YYYY-MM-DD" style="width: 240px" />
			</el-form-item>
			<el-form-item label="身份证" label-width="20%">
				<el-input v-model="updateEldrly.idCard" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="紧急联系人" label-width="20%" prop="emergencyContact">
				<el-input v-model="updateEldrly.emergencyContact" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="联系电话" label-width="20%" prop="phone">
				<el-input v-model="updateEldrly.phone" autocomplete="off" style="width: 240px" />
			</el-form-item>
			<el-form-item label="所在房间" label-width="20%">
				<el-select v-model="updateEldrly.rid" clearable placeholder="所在房间" style="width: 240px">
					<el-option v-for="item in roomAll" :key="item.rid" :label="item.rno" :value="item.rid" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="updateDialoadShowElderly = false">取消</el-button>
				<el-button type="primary" @click="updateByEldrly">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 修改老人对话框结束 -->
</template>
<script setup>
import elderlyApi from '@/api/admin/elderlyApi.js';
import { ElMessage } from 'element-plus';
import { ref, computed, reactive } from 'vue';
import { Minus, Plus } from '@element-plus/icons-vue'
import { View } from '@element-plus/icons-vue'
import roomApi from '@/api/admin/roomApi.js';
import { Search, UploadFilled } from '@element-plus/icons-vue'
import { useTokenStore } from '@/stores/token';
//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
const tokenStore = useTokenStore();
//上传图片
const headers = computed(() => {
	let token = tokenStore.tokenStr;
	return {
		token
	}
})
//定义一个用来接收全部老人的数据
const allElderly = ref([]);
const ename = ref('');
const eusername = ref('');
//定义控制显示对话框
const addDialoadShow = ref(false);
const eid = ref('');
//定义新增老人
const addElderly = ref({
	ename: "",
	eusername: "",
	epassword: "",
	egender: "",
	dateBirth: "",
	checkDate: "",
	idCard: "",
	emergencyContact: "",
	picdir: "",
	phone: "",
	rid: ""
});
const addElderlyFrom = ref(null)
const updateElderlyFrom = ref(null)
const addDialoadShowElderly = ref(false);
//定义修改项目
const updateEldrly = ref({});
//定义控制修改显示对话框
const updateDialoadShowElderly = ref(false);
//定义显示老人的详细信息的控件
const drawer = ref(false);
//定义显示修改老人对话框
const showUpdateEldrlyModel = (eid) => {
	//查询所有的房间
	roomApi.selectAllByElder()
		.then(resp => {
			if (resp.code == 10000) {
				roomAll.value = resp.data
			}
		})
	elderlyApi.selectByID(eid)
		.then(resp => {
			if (resp.code == 10000) {
				updateEldrly.value = resp.data;
				imageUrlUpdate.value = `${SERVER_ADDR.value}/upload/${resp.data.picdir}`
				updateDialoadShowElderly.value = true;
			} else {
				ElMessage.error(resp.msg)
			}
		})
}
//定义修改老人的方法
const updateByEldrly = () => {
	if (updateElderlyFrom.value) {
		updateElderlyFrom.value.validate((valid) => {
			if (valid) {
				elderlyApi.update(updateEldrly.value)
					.then(resp => {
						if (resp.code == 10000) {
							ElMessage.success(resp.msg)
							updateDialoadShowElderly.value = false
							selectAll(allElderly.value.pageNum);
						} else {
							ElMessage.error(resp.msg)
						}
					})
			}
		})
	}

}
//定义查询的所有房间
const roomAll = ref({});
//显示新建老人对话框
const showAddElderlyModel = () => {
	//查询所有的房间
	roomApi.selectAllByElder()
		.then(resp => {
			if (resp.code == 10000) {
				roomAll.value = resp.data
			}
		})
	addDialoadShowElderly.value = true
}
//新建老人
const insertByElderly = () => {
	if (addElderlyFrom.value) {
		addElderlyFrom.value.validate((valid) => {
			if (valid) {
				elderlyApi.insert(addElderly.value)
					.then(resp => {
						if (resp.code == 10000) {
							ElMessage.success(resp.msg)
							addDialoadShowElderly.value = false
							imageUrlAdd.value = '';
							addElderlyFrom.value.resetFields();
							selectAll(allElderly.value.pageNum);
							addElderly.value = {
								ename: "",
								eusername: "",
								epassword: "",
								egender: "",
								dateBirth: "",
								checkDate: "",
								idCard: "",
								emergencyContact: "",
								picdir: "",
								phone: "",
								rid: ""
							};
						} else {
							ElMessage.error(resp.msg)
						}
					})
			}
		})
	}

}
const elderlyInfo = ref({});
//获取老人的信息
const getElderlyInfo = (eid) => {
	elderlyApi.selectByID(eid)
		.then(resp => {
			if (resp.code == 10000) {
				elderlyInfo.value = resp.data
				drawer.value = true
				selectAll(allElderly.value.pageNum);
			}
		})
}
//删除老人
const deleteByeid = (eid) => {
	console.log(eid)
	elderlyApi.delete(eid)
		.then(resp => {
			if (resp.code == 10000) {
				ElMessage.success(resp.msg)
				selectAll(allElderly.value.pageNum);
			} else {
				ElMessage.error(resp.msg)
			}
		})
}
//查询所有的老人
const selectAll = (pageNum) => {
	elderlyApi.selectBypage(pageNum, ename.value, eusername.value)
		.then(resp => {
			allElderly.value = resp.data;
		})
}
const addEldList = ref([]);
const addMids = ref([]);
//显示已选护工的窜索框
const showAddEmpModel = (mname, eid2) => {
	eid.value = eid2
	//查询以及绑定的护工
	elderlyApi.selectMidsByeid(eid2)
		.then(resp => {
			addMids.value = resp.data
		})
	//查询所有的护工	
	elderlyApi.selectAllMedical(mname, eid2)
		.then(resp => {
			addEldList.value = resp.data
			addDialoadShow.value = true
		})
}
//穿梭框绑定护工
const addMedical = () => {
	elderlyApi.insertAddMedical(eid.value, addMids.value)
		.then(resp => {
			if (resp.code == 10000) {
				ElMessage.success(resp.msg)
				addDialoadShow.value = false
				selectAll(allElderly.value.pageNum);
			} else {
				ElMessage.error(resp.msg)
			}
		})
}
//导出项目
const uploadExcel = () => {
	elderlyApi.uploadExcel(elderly.value.pageNum, pname.value)
		.then(response => {
			ElMessage.success("正在下载Excel")
			// 请求成功返回后，获取到Excel文件的二进制数据
			const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
			// 创建下载链接
			const downloadUrl = URL.createObjectURL(blob);
			// 创建一个隐藏的a标签，设置下载链接和文件名，模拟点击下载
			const link = document.createElement('a');
			link.style.display = 'none';
			link.href = downloadUrl;
			link.download = '项目.xlsx';
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		}).catch(error => {
			// 请求失败处理
			console.error(error);
		})
}
const imageUrlAdd = ref("");
//头像上传的钩子函数
const handleAvatarSuccessAdd = (response, uploadFile) => {
	if (response.code == 10000) {

		ElMessage.success(response.msg);
		imageUrlAdd.value = `${SERVER_ADDR.value}/upload/${response.data}`;
		addElderly.value.picdir = response.data;
	}
}
const imageUrlUpdate = ref("");
const handleAvatarSuccessUpdate = (response, uploadFile) => {
	if (response.code == 10000) {

		ElMessage.success(response.msg);
		imageUrlUpdate.value = `${SERVER_ADDR.value}/upload/${response.data}`;
		updateEldrly.value.picdir = response.data;
	}
}
const uploadStudent = (resp) => {
	if (resp.code == 10000) {
		ElMessage.success(resp.msg)
	} else {
		ElMessage.error(resp.msg)
	}
}
const beforeAvatarUpload = (rawFile) => {
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('只能上传jpg格式的图片')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('图片大小不能超过2MB')
		return false
	}
	return true
}
//表单验证规则
const rules = reactive({
	eusername: [
		{ required: true, message: '请输入用户名', trigger: 'blur' },
		{ min: 5, max: 10, message: '用户名长度在 5 到 10 个字符', trigger: 'blur' }
	],
	ename: [
		{ required: true, message: '请输入姓名', trigger: 'blur' }
	],
	epassword: [
		{ required: true, message: '请输入密码', trigger: 'blur' },
		{ min: 5, max: 10, message: '密码长度在 5 到 10 个字符', trigger: 'blur' }

	],
	egender: [
		{ required: true, message: '请选择性别', trigger: 'change' }
	],
	emergencyContact: [
		{ required: true, message: '请输入联系方式', trigger: 'blur' },
		{ pattern: /^\d{6,11}$/, message: '联系方式格式不正确', trigger: 'blur' }
	],
	phone: [
		{ required: true, message: '请输入联系方式', trigger: 'blur' },
		{ pattern: /^\d{6,11}$/, message: '联系方式格式不正确', trigger: 'blur' }
	],
});
selectAll(1);
</script>
<style scoped>
.demo-progress .el-progress--line {
	margin-bottom: 10px;
	max-width: 100%;
}

.avatar-uploader,
.avatar {
	width: 178px;
	height: 178px;
	display: block;
	border: 1px dotted #dcdfe6;
	border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
}
</style>